<template>
    <div>
      <!-- 时间区间选择框 -->
      <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
        <el-select v-model="selectedRange" placeholder="请选择时间区间" @change="fetchData">
          <el-option label="近三天" value="3d"></el-option>
          <el-option label="近一周" value="7d"></el-option>
          <el-option label="近一个月" value="30d"></el-option>
        </el-select>
        <el-button type="primary" @click="exportData">导出数据</el-button>
      </div>
      <!-- eCharts 图表容器 -->
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, watch } from 'vue';
  import * as echarts from 'echarts';
  import axios from 'axios';
  import querystring from 'querystring';
  // 时间区间选择值
  const selectedRange = ref('3d');
  // eCharts 图表引用
  const chartRef = ref(null);
  // 图表实例
  let chart = null;
  
  // 计算开始和结束日期
  const calculateDateRange = (range) => {
    const endDate = new Date();
    let startDate = new Date();
    switch (range) {
      case '3d':
        startDate.setDate(endDate.getDate() - 3);
        break;
      case '7d':
        startDate.setDate(endDate.getDate() - 7);
        break;
      case '30d':
        startDate.setDate(endDate.getDate() - 30);
        break;
    }
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    return {
      startDate: formatDate(startDate),
      endDate: formatDate(endDate)
    };
  };
  const exportData = async () => {
    try {
      const { startDate, endDate } = calculateDateRange(selectedRange.value);
      const response = await axios.get('/api/admin/statistics/export', {
        responseType: 'blob'
      });
      
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `近三十天营业统计.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('导出数据失败:', error);
    }
  };
  // 获取数据
  const fetchData = async () => {
    const { startDate, endDate } = calculateDateRange(selectedRange.value);
    try {
      const response = await axios.get('/api/admin/statistics', {
        params: {
          startDate,
          endDate
        }
      });
      const data = response.data.data;
      updateChart(data);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };
  
  // 更新图表
  const updateChart = (data) => {
    const dates = data.map(item => item.day);
    const sales = data.map(item => item.sales);
    const completeRates = data.map(item => (item.completeRate * 100).toFixed(1) + '%');
  
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          return `日期: ${params.name}<br/>销售额: ${params.value}<br/>完单率: ${completeRates[params.dataIndex]}`;
        }
      },
      xAxis: {
        type: 'category',
        data: dates
      },
      yAxis: {
        type: 'value',
        name: '销售额'
      },
      series: [{
        data: sales,
        type: 'line',
        smooth: true
      }]
    };
  
    chart.setOption(option);
  };
  
  onMounted(() => {
    // 初始化 eCharts 图表
    chart = echarts.init(chartRef.value);
    fetchData();
  });
  
  // 导出数据
  

  // 监听时间区间选择变化
  watch(selectedRange, fetchData);
  </script>
  
  <style scoped>
  /* 这里可以添加统计后台页面的样式 */
  </style>